package com.lelefly.serlvet;

import java.io.File;
import java.util.Calendar;
import java.util.TimerTask;

import org.apache.log4j.Logger;

public class ClearDirTask extends TimerTask {
	private static final Logger logger = Logger.getLogger(ClearDirTask.class);
	private static final String tomcat_bin = System.getProperty("user.dir");
	private static final String tomcat_temp = tomcat_bin.substring(0,tomcat_bin.lastIndexOf("bin")) + "temp";
	private static final String tomcat_logs = tomcat_bin.substring(0,tomcat_bin.lastIndexOf("bin")) + "logs";
	private static final double overdays = 30;
	@Override
	public void run() {
		// TODO Auto-generated method stub
		logger.info("开始执行定期清理任务！");
		try {
			ClearDir(tomcat_temp);
			ClearDir(tomcat_logs);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private void ClearDir(String tomcatTemp) {
		// TODO Auto-generated method stub
		File dir = new File(tomcatTemp);
		if(dir.exists())
		{
			File[] files = dir.listFiles();
			Calendar current = Calendar.getInstance();
			for(File child:files)
			{
				if(child.isFile())
				{
					if(current.getTimeInMillis() - child.lastModified() > overdays*(1000*60*60*24))
					{
						if(child.delete())
						{
							logger.info("删除过期文件成功：" + child.getAbsolutePath());
						}
						else
						{
							logger.error("删除过期文件失败：" + child.getAbsolutePath());
						}
					}
				}
			}
		}
	}

}
